package deep10jvmdvm;

import utils.PrintlnUtils;

/*
代码中的 MyLock 就是一个最简单的独占锁，通过使用 MyLock 也能实现同 synchronized 和 ReentrantLock 相同的功能。比如如下代码：
 */
public class TestMyLock {
    static int count = 0;
    static MyLock myLock = new MyLock();


    public static void main(String[] args) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    myLock.lock();
                    int size = 10000;
                    for (int i = 0; i < size; i++) {
                        count++;
                    }

                } catch (Exception e) {

                } finally {
                    myLock.unlock();
                }
            }
        };

        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        PrintlnUtils.println("count = " + count);
        //  count = 20000
        //最终打印的 count 值为 20000，说明两个线程之间是线程安全的同步操作。

    }
}
